/*
 * JBoss, Home of Professional Open Source.
 * Copyright 2013, Red Hat, Inc., and individual contributors
 * as indicated by the @author tags. See the copyright.txt file in the
 * distribution for a full listing of individual contributors.
 *
 * This is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation; either version 2.1 of
 * the License, or (at your option) any later version.
 *
 * This software is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this software; if not, write to the Free
 * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
 */
package com.dzp.simpleSyslogServer.syslog;

import java.net.DatagramPacket;

import org.graylog2.syslog4j.server.impl.net.udp.UDPNetSyslogServer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.dzp.simpleSyslogServer.util.CommonUtil;

/**
 * udp 接收处理
 * 
 * @author dzp
 *
 */
public class UDPSyslogServer extends UDPNetSyslogServer {
	private static final Logger logger = LoggerFactory.getLogger(UDPSyslogServer.class);

	@Override
	public void shutdown() {
		super.shutdown();
		thread = null;
	}

	@Override
	public void run() {
		this.shutdown = false;
		try {
			this.ds = createDatagramSocket();
		} catch (Exception e) {
			logger.error("UDPSyslogServer error [Creating DatagramSocket failed]: {}", CommonUtil.getExceptionTrace(e));
			return;
		}

		// 用于接收数据
		byte[] receiveData = new byte[4096];

		while (!this.shutdown) {
			try {
				final DatagramPacket dp = new DatagramPacket(receiveData, receiveData.length);
				this.ds.receive(dp);
				SyslogEvent event = new SyslogEvent(receiveData, dp.getOffset(), dp.getLength(),
						dp.getAddress().getHostAddress());
				logger.debug("received udp syslog {} >>> {}", event.getClient_ip(), event.getMessage());
				logger.info("received udp syslog {} >>> length = {}", event.getClient_ip(),
						event.getMessage().length());
				/**
				 * 这里处理日志相关逻辑
				 */
			} catch (Exception e) {
				logger.error("UDPSyslogServer error : {}", CommonUtil.getExceptionTrace(e));
			}
		}
	}

}
